package cn.tedu.egmybatis6.controller;

import cn.tedu.egmybatis6.conmon.response.JsonResult;
import cn.tedu.egmybatis6.conmon.response.StataCode;
import cn.tedu.egmybatis6.mapper.UserMapper;
import cn.tedu.egmybatis6.pojo.dto.UserArticleDTO;
import cn.tedu.egmybatis6.pojo.dto.UserLoginDTO;
import cn.tedu.egmybatis6.pojo.entity.Article;
import cn.tedu.egmybatis6.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.Size;

@Slf4j
@Validated
@Api(tags = "用户模块")
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.error("userDTO:"+ userLoginDTO);
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        UserVO userVO = userMapper.loginSelect(username, password);
        log.error("userVO:"+ userVO);
        if (userVO !=null){
            session.setAttribute("user", userVO);
            return JsonResult.ok();
        }
        return new JsonResult(StataCode.USERNAME_PASSWORD_ERROR);
    }

    @ApiOperation("发表文章功能")
    @PostMapping("article")
    public JsonResult article(@RequestBody @Validated  UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        log.error("userVO:"+ userVO);
        if(userVO==null){
            return new JsonResult(StataCode.NOT_LOGIN);
        }
        Article article = new Article();
        article.setUserId(userVO.getId());
        article.setContent(userArticleDTO.getContent());
        article.setTitle(userArticleDTO.getTitle());
        log.error("article:"+ article);
        userMapper.InsertContent(article);
        return JsonResult.ok();
    }

    @ApiImplicitParam(name = "id",value = "文章id", required = true)
    @ApiOperation("查询指定文章功能")
    @GetMapping("selectByAticalId")
    public JsonResult selectByAticalId(@RequestParam @Range(
            min = 1, max = 100,message = "文章id应在1到100")  Long id){
        log.error("id:"+ id);
        return JsonResult.ok(userMapper.selectByAticalId(id));
    }
}
